﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.ServiceModel.Syndication;
using System.Speech.Recognition;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading;
using System.Threading.Tasks;
using System.Xml;

namespace DigiMate
{
	public class CurrencyService : BaseService
	{
		public CurrencyService()
		{
		}

		public override void Run(string text)
		{
			if (inProcess)
				return;

			inProcess = true;
			try
			{
				string url = System.Configuration.ConfigurationManager.AppSettings["RssURL.ExchangeRate"];
				RssXmlReader reader = new RssXmlReader(url);
				SyndicationFeed feed = SyndicationFeed.Load(reader);
				reader.Close();

				bool firstTime = true;
				if (feed.Items.Count() > 0)
				{
					foreach (SyndicationItem item in feed.Items)
					{
						if (firstTime)
						{
						}

						
						String subject = item.Title == null ? "" : item.Title.Text;
						String summary = item.Summary == null ? "no details" : Parse(item.Summary.Text);
						DateTime date = item.PublishDate.DateTime;

						if (subject == "")
							continue;

						//Speaker.SpeakOk(subject);
						Speaker.Speak(summary.Length > cutLongSummaryTo ? summary.Substring(0, cutLongSummaryTo) : summary);
					
					}
				}
				else
				{
					AddLog("No new messages in RSS");
				}
			}
			catch (Exception ex)
			{
				AddLog("There was a problem with rss: " + ex.Message);
			}
			finally
			{
				AddLog("Stopped.");

				inProcess = false;
			}
		}


		private string Parse(string text)
		{
			string re1 = "(1)";	// Integer Number 1
			string re2 = ".*?";	// Non-greedy match on filler
			string re3 = "(USD)";	// Word 1
			string re4 = ".*?";	// Non-greedy match on filler
			string re5 = "(=)";	// Any Single Character 1
			string re6 = ".*?";	// Non-greedy match on filler
			string re7 = "([+-]?\\d*\\.\\d+)(?![-+0-9\\.])";	// Float 1
			string re8 = ".*?";	// Non-greedy match on filler
			string re9 = "((?:[a-z][a-z]+))";	// Word 2

			Regex r = new Regex(re1 + re2 + re3 + re4 + re5 + re6 + re7 + re8 + re9, RegexOptions.IgnoreCase | RegexOptions.Multiline);
			Match m = r.Match(text);
			string res = "";
			if (m.Success)
			{
				String int1 = m.Groups[1].ToString();
				String word1 = m.Groups[2].ToString();
				String c1 = m.Groups[3].ToString();
				String float1 = m.Groups[4].ToString();
				String word2 = m.Groups[5].ToString();
				res = int1.ToString() + " " + word1.ToString() + " " + c1.ToString() + " " + float1.ToString() + " " + word2.ToString();
			}
			return res.ToLower();
		}
	}
}
